package com.slm.krstartimes.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.slm.krstartimes.R;
import com.slm.krstartimes.adapter.RelatedListAdapter;
import com.slm.krstartimes.utils.FormatCodeUtil;
import com.slm.krstartimes.utils.L;
import com.slm.krstartimes.utils.MyStringRequest;
import com.slm.krstartimes.utils.News;
import com.slm.krstartimes.utils.SearchDrawable;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends Activity implements OnClickListener, View.OnKeyListener, View.OnTouchListener, GestureDetector.OnGestureListener {
    boolean back = true;
    private AutoCompleteTextView autoTv;
    private Button startButton;
    private RelatedListAdapter relatedListAdapter;
    private ListView searchResult;
    private GestureDetector mGestureDetector;
    private int verticalMinDistance = 30;
    private int middleDistance = 150;
    private int minVelocity = 0;
    private LinearLayout search_layout;
    private SearchDrawable searchDrawable;
    private ImageView imageView;
    private Animation mStartAnimation;
    private long START_ANIMATION_DURATION = 600;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);

        initView();

        startButton.setOnClickListener(this);
        autoTv.setOnKeyListener(this);// 设置键盘监听
        search_layout.setOnTouchListener(this);
        mGestureDetector = new GestureDetector(this);
        search_layout.setLongClickable(true);

        initAutoComplete("history", autoTv);
        searchDrawable = new SearchDrawable();
        imageView.setImageDrawable(searchDrawable);
        startUpAnimation();
        imageView.setOnClickListener(this);
    }

    /**
     * 初始化
     */
    private void initView() {
        search_layout = (LinearLayout) findViewById(R.id.search_layout);
        autoTv = (AutoCompleteTextView) findViewById(R.id.startSearch);
        searchResult = (ListView) findViewById(R.id.searchResult);
        startButton = (Button) findViewById(R.id.startButton);
        imageView = (ImageView) findViewById(R.id.search);
    }

    @Override
    public void onClick(View v) {
        // 这里可以设定：当搜索成功时，才执行保存操作
        search(autoTv.getText().toString());
        saveHistory("history", autoTv);
        imageView.startAnimation(mStartAnimation);
        back = !back;
    }

    /**
     * 键盘事件监听,按下回车键开始搜索
     *
     * @param view
     * @param i
     * @param keyEvent
     * @return
     */
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (i == keyEvent.KEYCODE_ENTER) {
            search(autoTv.getText().toString());// 调用网络拉取方法,传入editText输入的关键字
            imageView.startAnimation(mStartAnimation);
            back = !back;
            return true;
        }
        return false;
    }


    /**
     * 初始化AutoCompleteTextView，最多显示5项提示，使
     * AutoCompleteTextView在一开始获得焦点时自动提示
     *
     * @param field 保存在sharedPreference中的字段名
     * @param auto  要操作的AutoCompleteTextView
     */
    private void initAutoComplete(String field, AutoCompleteTextView auto) {
        SharedPreferences sp = getSharedPreferences("network_url", 0);
        String longhistory = sp.getString("history", "nothing");
        String[] hisArrays = longhistory.split(",");
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, hisArrays);
        //只保留最近的50条的记录  
        if (hisArrays.length > 50) {
            String[] newArrays = new String[50];
            System.arraycopy(hisArrays, 0, newArrays, 0, 50);
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_dropdown_item_1line, newArrays);
        }
        auto.setAdapter(adapter);
        auto.setDropDownHeight(350);
        auto.setThreshold(1);
        auto.setCompletionHint("最近的5条记录");
        auto.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                AutoCompleteTextView view = (AutoCompleteTextView) v;
                if (hasFocus) {
                    view.showDropDown();
                }
            }
        });
    }


    /**
     * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
     *
     * @param field 保存在sharedPreference中的字段名
     * @param auto  要操作的AutoCompleteTextView
     */
    private void saveHistory(String field, AutoCompleteTextView auto) {
        String text = auto.getText().toString();
        SharedPreferences sp = getSharedPreferences("network_url", 0);
        String longhistory = sp.getString(field, "nothing");
        if (!longhistory.contains(text + ",")) {
            StringBuilder sb = new StringBuilder(longhistory);
            sb.insert(0, text + ",");
            sp.edit().putString("history", sb.toString()).commit();
        }

    }

    /**
     * 开始搜索
     *
     * @param key
     */
    private void search(String key) {//网络拉取方法,参数为关键字
        if (key.length() > 1) {
            String newTag = FormatCodeUtil.codingFormat(key.toString());
            L.i("开始搜索");
            MyStringRequest stringRequest = new MyStringRequest("http://www.ithome.com/json/tags/" + newTag + ".json",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {

                            if (s != null && s.length() > 2) {
                                String[] temp = s.split("=");
                                L.i("网络拉取成功"+s);
                                Gson gson = new Gson();
                                Type type = new TypeToken<ArrayList<News>>() {
                                }.getType();
                                final List<News> vartag_jsonp = gson.fromJson(temp[1], type);


                                relatedListAdapter = new RelatedListAdapter(SearchActivity.this, vartag_jsonp);


                                searchResult.setAdapter(relatedListAdapter);

                                searchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        Intent newsDetail = new Intent(SearchActivity.this, NewsDetailActivity.class);
                                        newsDetail.putExtra("newsId", vartag_jsonp.get(i).getNewsid());
                                        newsDetail.putExtra("title", vartag_jsonp.get(i).getNewstitle());
                                        newsDetail.putExtra("postdate", vartag_jsonp.get(i).getPostdate());
                                        L.i("点击了"+i);
                                        startActivity(newsDetail);
                                    }
                                });
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            });
            MainActivity.requestQueue.add(stringRequest);
        } else {
            Toast.makeText(this, "请输入关键字", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return mGestureDetector.onTouchEvent(motionEvent);
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    /**
     * 滑动返回
     *
     * @param e1
     * @param e2
     * @param v
     * @param v1
     * @return
     */
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(v) > minVelocity && (Math.abs(e2.getY() - e1.getY()) < middleDistance)) {
            L.i("滑动返回,"+e2+","+e1);
            finish();
        } else if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(v) > minVelocity && (Math.abs(e2.getY() - e1.getY()) < middleDistance)) {
            Toast.makeText(SearchActivity.this, "左滑", Toast.LENGTH_SHORT).show();
            L.i("滑动," + e2 + "," + e1);
        }
        return false;
    }

    /**
     * 开始动画
     */
    private void startUpAnimation() {
        mStartAnimation = new Animation() {
            @Override
            public void applyTransformation(float interpolatedTime, Transformation t) {
                if (back) {
                    searchDrawable.setPhase(1 - interpolatedTime);
                } else {
                    searchDrawable.setPhase(interpolatedTime);
                }
            }
        };
        mStartAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mStartAnimation.setDuration(START_ANIMATION_DURATION);
    }

}